<template>
  <div>
    <Header :isGoBack="false">
      <template v-slot:left>
        <div>
          {{ checkedBookData.edition_name }}- {{ checkedBookData.grade_name }}>
          {{ $store.getters.categoryList[category].title }}(极速模式)
        </div>
      </template>

      <template v-slot:right>
        <div class="test-btn">
          <span class="btn-bg ml20">
            <el-button class="button button-bg-second" @click="submitPaper"
              >交卷</el-button
            >
          </span>
          <span class="btn-bg ml20">
            <el-button
              class="button button-border-second"
              @click="goStudyCenter"
            >
              返回学习中心
            </el-button>
          </span>
        </div>
      </template>
    </Header>
    <div class="quick-test w1200">
      <div class="quick-test-banner flex-space-be">
        <span class="question-number">
          第{{ Number(nowAllIndex) + 1 }}题/共{{ questionNumber + 1 }}题
        </span>
        <span class="question-time">
          <img class="mr5" src="@/assets/img/test-time.png" alt="" />
          计时：{{ testTime | filterTime }}
        </span>
      </div>

      <div class="mt30">
        <el-tabs v-model="nowAllIndex" type="card">
          <el-tab-pane
            v-for="question in flattenQuestionList"
            :key="question.allIndex"
            :name="question.allIndex + ''"
          >
            <div
              slot="label"
              class="question-index"
              :class="question.studentAnswer ? 'is-answered' : ''"
            >
              {{ question.allIndex + 1 }}
            </div>
            <div class="question-container">
              <div class="question-header flex-space-be">
                <div class="left-type">
                  {{ typeObj[question.question_type] }}
                </div>
                <span class="number">
                  <b>{{
                    question.questionIndex >= 0
                      ? question.questionIndex + 1
                      : questionList[question.typeIndex - 1].question_info_list
                          .length
                  }}</b>
                  /
                  {{
                    questionList[question.typeIndex]
                      ? questionList[question.typeIndex].question_info_list
                          .length
                      : questionList[question.typeIndex - 1].question_info_list
                          .length
                  }}
                </span>
                <span
                  v-if="
                    question.question_type == 1 ||
                      question.question_type == 2 ||
                      question.question_type == 3
                  "
                >
                  温馨提示：四个选项分别对应快捷键1/2/3/4，按“Enter”进入下一题。
                </span>
                <span v-else> 温馨提示：按“Enter”进入下一题。 </span>
              </div>
              <div
                class="question-box mt20"
                :class="
                  question.question_type == 4 || question.question_type == 5
                    ? 'write-question'
                    : ''
                "
              >
                <TestQuestion
                  :isQuick="true"
                  :question="question"
                  @changeStudentAnswer="changeStudentAnswer"
                  :ref="'question-' + question.allIndex"
                ></TestQuestion>
              </div>
              <div class="btn-box mt20">
                <el-button
                  class="button-bg-primary button"
                  v-if="question.allIndex == questionNumber"
                  @click="submitPaper"
                >
                  交卷
                </el-button>
                <el-button
                  v-else
                  class="button-bg-primary button"
                  @click="nextQuestionThrottle"
                >
                  下一题
                </el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>
<script>
import Header from "@/components/Header";
import TestQuestion from "../components/TestQuestion";
import { getPaperData, startPaperTest, checkPaperData } from "@/api/index";
import { throttle } from "@/utils/utils";
import EventBus from "@/assets/js/eventBus";
export default {
  data() {
    return {
      paperData: {},
      questionList: [],
      flattenQuestionList: [],
      typeObj: {
        0: "记忆",
        1: "英译汉",
        2: "汉译英",
        3: "听力理解",
        4: "听写",
        5: "默写",
      },

      testTime: 0,
      timer: null,
      nowQuestion: {
        allIndex: 0,
      },
      questionNumber: 0, //总题数
      nowTypeIndex: 0,
      nowQuestionIndex: -1,
      nowAllIndex: 0,
      unitId: null,
      category: null,
      source: null,
      checkedBookData: null,
      isOpenMessageBox: false,
      submitReminder: true,
    };
  },

  methods: {
    goStudyCenter() {
      this.$confirm(`试卷还未提交，是否退出`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })
        .then(() => {
          if (this.$route.query.backName) {
            this.$router.push({
              name: "naturalSpell",
            });
            return;
          }
          this.$router.push({
            name: "studyCenter",
          });
        })
        .catch(() => {
          return false;
        });
    },
    getTestPaper() {
      let data = {
        category: this.category,
        book_id: this.checkedBookData.book_id,
        unit_id_list: this.unitId, //2229 2230
        mode: 1,
        source: this.source,
      };
      if (this.category == 24) {
        data.question_type_list = this.$route.query.questionType
          ? String(this.$route.query.questionType).split(",")
          : [1, 2, 3, 4, 5];
      }
      EventBus.$emit("openLoading", {});
      getPaperData(data)
        .then((res) => {
          EventBus.$emit("closeLoading");
          if (res.code == 200) {
            startPaperTest({
              english_test_id: res.data.english_test_id,
            }).then((res1) => {
              if (res1.code == 200) {
                this.testTime = 0;
                this.timerFun();
              }
            });
            this.paperData = res.data;
            this.questionList = res.data.question_info_type_list;
            let allIndex = -1;
            this.questionList.forEach((questionType, typeIndex) => {
              questionType.question_info_list.forEach(
                (question, questionIndex) => {
                  question.studentAnswer = "";
                  allIndex++;
                  question.allIndex = allIndex;
                  question.typeIndex = typeIndex;
                  question.questionIndex = questionIndex;
                  question.phonetic =
                    this.$store.getters.isBritish == 1
                      ? question.phonetic_british
                      : question.phonetic_american; //音标
                  question.audioURL =
                    this.$store.getters.isBritish == 1
                      ? question.en_url
                      : question.us_url; //音频
                  this.flattenQuestionList.push(question);
                }
              );
            });
            this.questionNumber = allIndex;
            this.focusOrPlay(this.nowAllIndex);
          }
        })
        .catch(() => {
          EventBus.$emit("closeLoading");
        });
    },
    timerFun() {
      this.timer = setInterval(() => {
        this.testTime++;
        if (
          this.testTime > this.paperData.test_time - 10 &&
          // this.testTime <= 10 &&
          this.submitReminder &&
          !this.isOpenMessageBox
        ) {
          this.isOpenMessageBox = true;
          this.submitReminder = false;
          this.$confirm("考试即将超时,请尽快交卷", "提示", {
            confirmButtonText: "交卷",
            cancelButtonText: "取消",
            beforeClose: (action, instance, done) => {
              this.isOpenMessageBox = false;
              done();
            },
          })
            .then(() => {
              clearInterval(this.timer);
              this.postPaper();
            })
            .catch(() => {});
        } else if (this.testTime >= this.paperData.test_time - 3) {
          clearInterval(this.timer);
          this.postPaper();
          this.$msgbox.close();
        }
      }, 1000);
    },
    submitPaper() {
      let number = 0;
      this.flattenQuestionList.forEach((question) => {
        if (!question.studentAnswer) {
          number++;
        }
      });
      if (!this.isOpenMessageBox) {
        this.isOpenMessageBox = true;
        this.$confirm(
          `${number > 0 ? "还有" + number + "道题未答，" : ""}
        是否检查完毕，确认提交？`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            beforeClose: (action, instance, done) => {
              this.isOpenMessageBox = false;
              console.log(this);
              done();
            },
          }
        )
          .then(() => {
            this.postPaper();
          })
          .catch(() => {
            return false;
          });
      }
    },
    postPaper() {
      clearInterval(this.timer);
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (
            question.question_type == 1 ||
            question.question_type == 2 ||
            question.question_type == 3
          ) {
            let answer = question.answer_list.filter((answer) => {
              return (
                question.studentAnswer ==
                (answer.word_id || answer.word_name || answer.paraphrase)
              );
            });
            question.student_answer_list = answer;
          } else if (
            question.question_type == 4 ||
            question.question_type == 5
          ) {
            question.student_answer_list = question.studentAnswer
              ? [{ word_name: question.studentAnswer }]
              : [];
          }
        });
      });
      // let useTime = this.paperData.test_time - this.testTime;
      let useTime = this.testTime;
      let data = {
        english_test_id: this.paperData.english_test_id,
        book_id: this.checkedBookData.book_id,
        source: this.source,
        use_time: useTime,
        unit_id_list: this.unitId,
        student_question_info_list: this.questionList,
      };
      EventBus.$emit("openLoading", {});
      this.isOpenMessageBox = true;
      checkPaperData(data)
        .then((res) => {
          this.isOpenMessageBox = false;
          EventBus.$emit("closeLoading");
          if (res.code == 200 && res.data && res.data.question_info_type_list) {
            this.testLoading = true;
            res.data.test_time = this.paperData.test_time;
            res.data.useTime = useTime;
            localStorage.setItem("paperRes", JSON.stringify(res));
            clearInterval(this.timer);
            this.$router.push({
              name: "testReport",
              query: this.$route.query,
            });
          } else if (res.data.is_finish) {
            this.$alert("考试已结束");
          }
        })
        .catch(() => {
          this.isOpenMessageBox = false;
          EventBus.$emit("closeLoading");
        });
    },
    nextQuestion() {
      if (this.nowAllIndex < this.questionNumber) {
        this.nowAllIndex = Number(this.nowAllIndex) + 1 + "";
      } else {
        // 交卷
        this.submitPaper();
      }
    },

    nextQuestionThrottle: throttle(function() {
      this.nextQuestion();
    }, 500),
    watchKeyDown(e) {
      let nowQuestion = this.flattenQuestionList[this.nowAllIndex];
      // console.log(e);
      if (this.isOpenMessageBox) {
        return;
      }
      if (e.keyCode == 17) {
        //Control
        if (this.$refs[`question`]) {
          this.$refs[`question`].playAudio();
        }
      }
      if (e.keyCode == 13) {
        //  Enter
        this.stopEvent(e);
        this.nextQuestionThrottle();
      }
      if (
        nowQuestion.question_type == 1 ||
        nowQuestion.question_type == 2 ||
        nowQuestion.question_type == 3
      ) {
        if (e.keyCode == 49 || e.keyCode == 97) {
          this.checkAnswer(1);
        }
        if (e.keyCode == 50 || e.keyCode == 98) {
          this.checkAnswer(2);
        }
        if (e.keyCode == 51 || e.keyCode == 99) {
          this.checkAnswer(3);
        }
        if (e.keyCode == 52 || e.keyCode == 100) {
          this.checkAnswer(4);
        }
      }
      //97-100
    },
    //阻止默认事件
    stopEvent(e) {
      if (e && e.preventDefault) {
        e.preventDefault();
      } else {
        window.event.returnValue = false;
      }
    },
    // 1/2/3/4选择选项
    checkAnswer(num) {
      let nowQuestion = this.flattenQuestionList[this.nowAllIndex];
      if (nowQuestion.answer_list && nowQuestion.answer_list[num - 1]) {
        let answer = nowQuestion.answer_list[num - 1];
        if (
          this.$refs[`question-${nowQuestion.allIndex}`] &&
          this.$refs[`question-${nowQuestion.allIndex}`][0]
        ) {
          this.$refs[`question-${nowQuestion.allIndex}`][0].studentAnswer =
            answer.word_id || answer.word_name || answer.paraphrase;

          this.$refs[
            `question-${nowQuestion.allIndex}`
          ][0].changeStudentAnswer();
        }
      }
    },
    changeStudentAnswer(studentAnswer, allIndex) {
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (question.allIndex == allIndex) {
            question.studentAnswer = studentAnswer;
            return;
          }
        });
      });
    },
    focusOrPlay(newIndex) {
      let nowQuestion = this.flattenQuestionList[this.nowAllIndex];
      if (!nowQuestion) {
        return;
      }
      this.$nextTick(() => {
        if (
          this.$refs[`question-${newIndex}`] &&
          this.$refs[`question-${newIndex}`][0]
        ) {
          this.$refs[`question-${newIndex}`][0].inputFocus();
        }
        if (
          (nowQuestion.question_type == 3 || nowQuestion.question_type == 4) &&
          this.$refs[`question-${newIndex}`] &&
          this.$refs[`question-${newIndex}`][0]
        ) {
          this.$refs[`question-${newIndex}`][0].playAudio();
        }
      });
    },
  },
  filters: {
    filterTime(val) {
      let hours = parseInt(val / 3600);
      if (hours < 10) {
        hours = "0" + hours;
      }
      let minutes = parseInt((val % 3600) / 60);
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      let seconds = parseInt(val % 60);
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
      return hours + ":" + minutes + ":" + seconds;
    },
  },

  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.category = Number(this.$route.query.category);
    this.source = this.$store.getters.categoryList.filter((item) => {
      return item.category == this.category;
    })[0].source;
    this.unitId = this.$route.query.unitId
      ? String(this.$route.query.unitId).split(",")
      : null;
    this.getTestPaper();
  },
  mounted() {
    window.addEventListener("keydown", this.watchKeyDown);
  },
  beforeDestroy() {
    window.removeEventListener("keydown", this.watchKeyDown);
    clearInterval(this.timer);
    if (this.isOpenMessageBox) {
      this.$msgbox.close();
    }
  },
  components: {
    Header,
    TestQuestion,
  },
  watch: {
    nowAllIndex(newIndex) {
      this.focusOrPlay(newIndex);
    },
  },
};
</script>
